<template>
    <van-nav-bar title="登录" class="page-nav-bar">
        <template #left>
            <van-icon name="cross" size="18" @click="this.$router.back()" />
        </template>
    </van-nav-bar>
    <van-form @submit="onSubmit">


        <van-field name="userName" label="用户名" placeholder="用户名" left-icon="manager" v-model="userName"
            :rules="userFormRules.userName" />

        <van-field type="password" name="userPwd" label="密码" placeholder="密码" left-icon="lock" v-model="userPwd"
            :rules="userFormRules.userPwd" />

        <div style="margin: 16px;">
            <van-button block type="primary" native-type="submit">
                登录
            </van-button>
        </div>
    </van-form>

   
</template>
<script>
import { reactive, toRefs } from 'vue';
import { login } from "../../api/user";

import { showLoadingToast } from 'vant';
import { showSuccessToast, showFailToast } from 'vant';
import 'vant/es/toast/style';
import { useStore } from "vuex";
import router from  "../../router"

//构建登录请求
//2获取用户名和密码发送到服务端

function userSubmit(user) {
    const store = useStore();
    const onSubmit = async () => {

        showLoadingToast({
            message: '登录中...',
            forbidClick: true,
        });

       
        const res = await login(user);
        console.log("onSubmit fun at login/index.vue back res",res.data);
        if (res.data.code === 1) {
            store.commit("setUser", res.data)
            showSuccessToast('登录成功');
            router.push("/my");
            //console.log("login success");
        }
        else {
            showFailToast('用户名密码不正确');
            //console.log("login error");
        }
    };
    const userFormRules = {
        userName: [{ required: true, message: "请输入用户名" }],
        userPwd: [
            { required: true, message: "请输入密码" },
            { pattern: /^.{6}$/, message: "密码格式格式" }
        ],
    };

    return { onSubmit, userFormRules };
}



export default {

    setup() {

        const user = reactive({
            userName: "",
            userPwd: ""
        })
        return {
            ...toRefs(user),
            ...userSubmit(user),
        };

    }

};
</script>
<style>

</style>